package com.edu.framework.websocket.service;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONObject;
import com.edu.framework.websocket.WebSocketHolder;
import com.edu.framework.websocket.assemble.message.MessageAssemble;
import com.edu.framework.websocket.assemble.message.TriggerMsgEngine;
import com.edu.framework.websocket.message.base.Message;
import com.edu.framework.websocket.message.base.Response;
import com.edu.framework.websocket.message.notice.NoticeRequest;
import com.edu.framework.websocket.message.notice.NoticeVO;
import com.edu.system.service.ITNoticeService;
import com.edu.system.service.ITPublishClassService;
import com.edu.system.service.ITTerminalService;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @program: xxxx
 * @description:
 * @author: zlh
 * @create: 2024-01-06 18:20
 **/
@Slf4j
@Component
public class NoticeService implements MessageAssemble {

  @Resource
  private ITPublishClassService publishClassService;
  @Resource
  private ITNoticeService itNoticeService;
  @Resource
  private ITTerminalService itTerminalService;
  @Value("${image.host}")
  private String imageHost;

  // 通知// 1通知 2校园风采
  public static final Integer PUBLISH_CLASS_TYPE=1;
  // 1普通通知 2 强通知
  private static final Integer NOTICE_TYPE_NORMAL = 1;
  private static final Integer NOTICE_TYPE_FORCE = 2;

  private List<Long> noticeIds;
  /**
   * 普通通知
   * @param roomId
   * @return
   */
  public Response<List<NoticeVO>> getNoticeList(Long roomId){
    if (roomId == null){
      return null;
    }
    List<Long> ids = publishClassService.queryIdsByRoomId(roomId, PUBLISH_CLASS_TYPE);

    List<NoticeVO> vo = itNoticeService.liveListByIds(ids, NOTICE_TYPE_NORMAL)
        .stream()
        .map(a -> NoticeVO.builder().id(a.getId()).title(a.getTitle()).build())
        .collect(Collectors.toList());

    this.noticeIds = vo.stream().map(NoticeVO::getId).collect(Collectors.toList());
    return Response.ok(NoticeRequest.TYPE, NoticeRequest.RESP_KEY, vo);
  }

  /**
   * 详情
   * @param noticeId
   * @return
   */
  public NoticeVO getNoticeDetail(Long noticeId){
    return Optional.ofNullable(itNoticeService.selectTNoticeById(noticeId))
        .map(a -> NoticeVO.builder()
            .id(a.getId())
            .title(a.getTitle())
            .content(StrUtil.replace(a.getContent(), "/prod-api", imageHost))
            .build()
        )
        .orElseGet(NoticeVO::new);
  }

  /**
   * 下发通知
   * @param classIds
   * @throws IOException
   */
  public void pushMsg(List<Long> classIds) {
    Map<String, Long> codeMapId = itTerminalService.codeIdMapByLocationIds(classIds, "班牌");
    // 查
    Function<String, Message> fc = code -> {
      log.info("机器:{}", code);
      Response<List<NoticeVO>> vo = getNoticeList(codeMapId.getOrDefault(code, null));
      log.info("普通通知：{}", JSONObject.toJSONString(vo));
      return vo;
    };
    // 成功后回调
    Consumer<Message> invoke = message -> itNoticeService.publishStatusToOn(this.noticeIds);
    try {
      WebSocketHolder.broadcast(fc, invoke);

    } catch (Exception e){
      log.error("主动下发失败 推送通知", e);
    }
  }

  @Override
  public void buildTrigger(List<Long> firstClassIds) {
    TriggerMsgEngine.addEveryRun(NoticeService.class.getSimpleName());

//    Date date = new Date();
//    DateTime beginTime = DateUtil.offsetSecond(DateUtil.beginOfDay(date), -1);
//    DateTime endTime = DateUtil.endOfDay(date);
//
//    List<TNotice> tNotices = itNoticeService.queryTodayChangeList();
//    String clsName = NoticeService.class.getSimpleName();
//    String forceClsName = ForceNoticeService.class.getSimpleName();
//    List<MsgCacheDTO> collect = tNotices.stream()
//        .flatMap(a -> {
//          List<Long> classIds = publishClassService.queryClassIdsByTid(a.getId(), PUBLISH_CLASS_TYPE);
//          List<MsgCacheDTO> d = new ArrayList<>();
//          String cls = null;
//          if (a.getType().equals(NOTICE_TYPE_NORMAL)){
//            cls = clsName;
//          } else {
//            cls = forceClsName;
//          }
//
//          if (a.getNoticeStartTime().after(beginTime) && a.getNoticeStartTime().before(endTime)) {
//            d.add(MsgCacheDTO.builder().triggerTime(a.getNoticeStartTime()).clsName(cls)
//                .classIds(classIds).build());
//          }
//          if (a.getNoticeEndTime().after(beginTime) && a.getNoticeEndTime().before(endTime)) {
//            d.add(MsgCacheDTO.builder().triggerTime(a.getNoticeEndTime()).clsName(cls)
//                .classIds(classIds).build());
//          }
//          return d.stream();
//        }).collect(Collectors.toList());
//    // 优先下发
//    if (CollectionUtils.isNotEmpty(firstClassIds)){
//      collect.add(MsgCacheDTO.builder().triggerTime(new Date()).clsName(clsName).classIds(firstClassIds).build());
//    }
//    // 装填
//    TriggerMsgEngine.addMsgDate(collect);
  }


}
